import React, { Component } from 'react'
import PropTypes from 'prop-types'

export default class TodoListDemo extends Component {
  constructor(props) {
    super(props)
    this.state = {
      list: [
        {
          id: 'id-1',
          title: '标题1'
        },
        {
          id: 'id-2',
          title: '标题2'
        },
        {
          id: 'id-3',
          title: '标题3'
        }
      ],
      footerInfo: '底部文字'
    }
  }

  render() {
    return (
      <div>
        <Input submitTitle={this.onSubmitTitle}></Input>
        <List list={this.state.list}></List>
        <Footer text={this.state.footerInfo}></Footer>
      </div>
    )
  }

  onSubmitTitle = (title) => {
    console.log(title);
    this.setState({
      list: this.state.list.concat({
        id: `id-${Date.now()}`,
        title
      })
    })


  }
}


class List extends Component {
  constructor(props) {
    super(props)
  }

  render() {
    const { list } = this.props

    return (
      <div>
        <ul>
          {list.map(item => {
            return (
              <li key={item.id}>{item.title}</li>
            )
          })}
        </ul>
      </div>
    )
  }
}

List.propTypes = {
  list: PropTypes.arrayOf(PropTypes.object).isRequired
}

// 输入组件 
class Input extends Component {
  constructor(props) {
    super(props)
    this.state = {
      title: ''
    }
  }

  render() {
    return (
      <div>
        <input type="text" value={this.state.title} onChange={this.handelInput} />
        <p>{this.state.title}</p>
        <button onClick={this.submit}>添加</button>
      </div>
    )
  }
  submit = () => {
    const { submitTitle } = this.props
    submitTitle(this.state.title)
    this.setState({
      title: ''
    })
  }

  handelInput = (e) => {
    this.setState({
      title: e.target.value
    })
  }
}

Input.propTypes = {
  submitTitle: PropTypes.func.isRequired
}

class Footer extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    return (
      <div>
        <p>
          {this.props.text}
          {this.props.length}
        </p>
      </div>
    )
  }

  // React默认父组件有更新，子组件也无条件更新
  // 性能优化对于React更加重要
  // SCU一定要用么？不一定-需要优化是才会去用

  // shouldComponentUpdate(nextProps, nextState) {
  //   if (nextProps.text !== this.props.text) {
  //     return true
  //   }
  //   return false
  // }

  componentDidUpdate() {
    console.log('footer did updated');
  }

}

